#include <AppendFile.hpp>
namespace FileUtil
{
	/// --------------------------------------------------------------------------------
	/// @brief: 
	/// --------------------------------------------------------------------------------
	AppendFile::AppendFile(const std::string filename)
		: fp_(::fopen(filename.c_str(), "w+")),  // 'e' for O_CLOEXEC
		writtenBytes_(0)
	{
		if (fp_)
		{
			std::setbuf(fp_, buffer_);
		}
		
	}

	/// --------------------------------------------------------------------------------
	/// @brief: 
	/// --------------------------------------------------------------------------------
	AppendFile::~AppendFile()
	{
		if (fp_)
		{
			fclose(fp_);
			fp_ = nullptr;

		}
	}

	/// --------------------------------------------------------------------------------
	/// @brief: 
	/// --------------------------------------------------------------------------------
	void AppendFile::setFile(const std::string filename)
	{
		fp_ = ::fopen(filename.c_str(), "w+");
	}

	/// --------------------------------------------------------------------------------
	/// @brief: 
	/// --------------------------------------------------------------------------------
	void AppendFile::append(const char* logline, size_t len)
	{
		if (true != write(logline, len))
		{
			return;
		}

		writtenBytes_ += len;
	}

	/// --------------------------------------------------------------------------------
	/// @brief: 
	/// --------------------------------------------------------------------------------
	void AppendFile::flush()
	{
		if (fp_)
		{
			fflush(fp_);
		}
	}

	/// --------------------------------------------------------------------------------
	/// @brief: 
	/// --------------------------------------------------------------------------------
	bool AppendFile::write(const char* logline, size_t len)
	{
		if (nullptr == fp_)
		{
			return false;
		}

		if (1 != fwrite(logline, len, 1, fp_))
		{
			return false;
		}

		return true;
	}

}